<template>
  <div class="app-container">

    <!-- 条件搜索 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="组件名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入组件名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="组件类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择组件类型" clearable>
          <el-option
            v-for="dict in networkTypes"
            :key="dict.id"
            :label="dict.name"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="启停状态" prop="startState">
        <el-select v-model="queryParams.startState" placeholder="请选择组件状态" clearable>
          <el-option
            v-for="dict in dict.type.iot_network_state"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 新增、修改、删除、导出功能按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['iot:network:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleDelete"
          v-hasPermi="['iot:network:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['iot:network:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 组件列表 -->
    <el-table v-loading="loading" :data="networkList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="组件名称" align="center" prop="name"/>
      <el-table-column label="网络地址" align="center" prop="host">
        <template slot-scope="scope">
          {{ getTableNetworkAddress(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column label="组件类型" align="center" prop="type">
        <template slot-scope="scope">
          {{ getTableNetworkType(scope.row) }}
        </template>
      </el-table-column>

      <el-table-column label="启停状态" align="center" prop="startState">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.startState"
            active-value="enabled"
            inactive-value="disabled"
            @change="handleStartStopChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>

      <el-table-column label="组件描述" align="center" prop="description"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.startState === 'enabled'"
            size="mini"
            type="text"
            @click="handleDebugging(scope.row)"
            v-hasPermi="['iot:network:list']"
          >
            <svg-icon icon-class="bug"/>
            调试
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['iot:network:edit']"
          >修改
          </el-button>
          <el-button
            v-if="scope.row.startState === 'disabled'"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['iot:network:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页-->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList()"
    />

    <!-- 添加或修改组件对话框 -->
    <network-add-edit @submit="handleSubmit" ref="networkAddEdit"/>

    <!--调试对话框-->
    <network-debug ref="networkDebugging"></network-debug>

  </div>
</template>

<script>
import { listNetwork, delNetwork, startupNetwork, shutdownNetwork, getNetworkType } from '@/api/iot/network'
import NetworkAddEdit from './networkAddEdit'
import NetworkDebug from './networkDebug'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  name: 'Network',
  components: {
    NetworkAddEdit,
    NetworkDebug
  },
  dicts: ['iot_network_state'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      names: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 产品表格数据
      networkList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        type: null,
        startState: null,
        description: null
      },
      // 网络组件类型
      networkTypes: []
    }
  },
  created() {
    this.getNetworkType().then(() => {
      this.getList()
    })
  },
  methods: {
    /** 查询组件列表 */
    getList() {
      this.loading = true
      listNetwork(this.queryParams).then(response => {
        this.networkList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 启用状态修改 */
    handleStartStopChange(row) {
      let text = row.startState === 'enabled' ? '启用' : '停止'
      this.$modal.confirm(`确认要${text}${row.name}组件吗？`).then(function() {
        if (row.startState === 'enabled') {
          startupNetwork(row.id)
        }
        if (row.startState === 'disabled') {
          shutdownNetwork(row.id)
        }
      }).then(() => {
        this.$modal.msgSuccess(text + '成功')
      }).catch(function() {
        row.startState = row.startState === 'enabled' ? 'disabled' : 'enabled'
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.names = selection.map(item => item.name)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      const names = row.name || this.names
      this.$modal.confirm('是否确认删除组件名称为"' + names + '"的数据项？').then(function() {
        return delNetwork(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('iot/network/export', {
        ...this.queryParams
      }, `network_${new Date().getTime()}.xlsx`)
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$refs.networkAddEdit.handleAddNetwork()
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const id = row.id || this.ids
      this.$refs.networkAddEdit.handleUpdate(id, row.startState)
    },

    /** 表单提交 */
    handleSubmit() {
      this.getList()
    },

    /** 调试按钮操作 */
    handleDebugging(row) {
      this.$refs.networkDebugging.handleDebugging(row)
    },

    /** 获取网络组件类型 */
    getNetworkType() {
      return new Promise(resolve => {
        getNetworkType().then(({ data }) => {
          this.networkTypes = data || []
          resolve(data)
        })
      })

    },

    /** 组件类型 */
    getTableNetworkType(data) {

      if (!data) {
        return
      }

      const findData = this.networkTypes.find(item => item.id === data.type)

      if (!findData) {
        return
      }

      data.typeName = findData.name

      return findData.name
    },

    /** 获取网络地址 */
    getTableNetworkAddress(data) {

      if (!data) {
        return
      }

      const shareCluster = data.shareCluster

      if (shareCluster) {
        if (data.type === 'TCP_CLIENT') {
          const configuration = JSON.parse(data.configuration) || []
          let addresses = []
          configuration.addresses.forEach(address => {
            addresses.push(`/${address.host}:${address.port}`)
          })
          return JSON.stringify(addresses)
        }else {
          const configuration = JSON.parse(data.configuration)
          return `/${configuration.host}:${configuration.port}`
        }

      }else {
        const cluster = JSON.parse(data.cluster) || []
        let addresses = []
        if (data.type === 'TCP_CLIENT') {
          cluster.forEach(({ configuration }) => {
            if (!configuration.addresses) {
              return
            }
            configuration.addresses.forEach(address => {
              addresses.push(`/${address.host}:${address.port}`)
            })
          })
        }else {
          cluster.forEach(configuration => {
            addresses.push(`/${configuration.configuration.host}:${configuration.configuration.port}`)
          })
        }
        return JSON.stringify(addresses)

      }

    }

  }
}
</script>
